package cn.net.isir.service2;

import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.pay.alipay.AlipayAPI;
import cn.net.isir.core.BasicService2;
import cn.net.isir.core.SetBasicDao;
import cn.net.isir.dao.AlipayAuthDao;
import cn.net.isir.dao.PaymentDao;
import cn.net.isir.dao.ShopDao;
import cn.net.isir.entity.AlipayAuth;
import cn.net.isir.entity.Payment;
import cn.net.isir.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AlipayAuthService extends BasicService2<AlipayAuth> {
    @SetBasicDao
    @Resource
    private AlipayAuthDao alipayAuthDao;
    @Resource
    private ShopDao shopDao;
    @Resource
    private AlipayOpenAgentFacetofaceSignService alipayOpenAgentFacetofaceSignService;
    @Resource
    private PaymentDao paymentDao;


    /**
     * 子商户授权给服务商
     *
     * @param userId      操作人
     * @param appId       应用id
     * @param paymentId   支付手段id
     * @param appAuthCode 授权码
     * @return 授权结果
     */
    public ResultObject alipayAuthRedirect(String userId, String appId, String paymentId, String appAuthCode) {
        //1.保存t_alipay_auth表的app_auth_code（insert操作在换取app_auth_token之后执行）
        AlipayAuth auth = new AlipayAuth();
        auth.setShopId(paymentId);
        auth.setApp_auth_code(appAuthCode);
//        auth.setApp_auth_token(null);
//        auth.setUser_id(userId);
        auth.setAuth_app_id(appId);
//        auth.setApp_refresh_token();
        auth.setCreateUser(userId);
        //2.使用app_auth_code换取app_auth_token,
        AlipayOpenAuthTokenAppResponse response =
                AlipayAPI.alipayOpenAuthTokenApp("authorization_code", appAuthCode, null);
        if (response == null) {
            logger.info("支付宝换取authToken错误");
            return new ResultObject(500, "fail", null);
        }
        auth.setUser_id(response.getUserId());
        auth.setApp_auth_token(response.getAppAuthToken());
        auth.setApp_refresh_token(response.getAppRefreshToken());
        //3.保存app_auth_token和userid
        alipayAuthDao.insert(auth);

        //更新其他授权中，此支付宝用户的token
        AlipayAuth alipayAuth = new AlipayAuth();
        alipayAuth.setUser_id(response.getUserId());
        List<AlipayAuth> authList = alipayAuthDao.selectList(alipayAuth);
        if (authList != null && authList.size() > 0) {
            authList.forEach(item -> {
                if (StringUtils.isNotBlank(item.getApp_auth_token())) {
                    item.setApp_auth_token(response.getAppAuthToken());
                    item.setApp_refresh_token(response.getAppRefreshToken());
                    alipayAuthDao.update(item);
                }
            });
        }

        //改：更新支付手段中的支付宝部分信息
        Payment payment = paymentDao.selectByPrimaryKey(paymentId);
        payment.setName("支付宝支付-" + response.getUserId());
        payment.setAuthAccount(response.getUserId());
        payment.setBindingAuthInfoId(auth.getId());
        paymentDao.update(payment);

//        //4.判断是否已经保存当面付资料，如果已经保存了，直接提交到支付宝，否则不提交
//        Shop shop = shopDao.selectByPrimaryKey(shopId);
//        //更新店铺表中，授权用户id和授权状态
//        shop.setAlipayMerchantId(response.getUserId());
//        shop.setAlipayAuthStatus("1");
////        shop.setAlipayBusinessInfo();
//        shopDao.update(shop);
//        //查询是否有已经使用此商户正常授权并签约的
//        Shop shop1 = new Shop();
//        shop1.setAlipayMerchantId(response.getUserId());
//        shop1.setAlipaySignStatus("3");
//        List<Shop> signShopList = shopDao.selectList(shop1);
//        //如果没有，则进行签约
//        if (signShopList == null || signShopList.size() == 0) {
//            if (StringUtils.isNotBlank(shop.getAlipayBusinessInfo())) {
//                //提交资料
//                ResultObject ro = alipayOpenAgentFacetofaceSignService.submitOpenAgentFacetofaceSignInfo(shopId);
//                if (ro.getResult() != 200) {
//                    return ro;
//                }
//            }
//        }
//
//        //如果已经有此账号签约并成功，则直接成功
//        if (signShopList != null && signShopList.size() > 0) {
//            shop.setAlipaySignStatus("3");
//            shopDao.update(shop);
//        }

        return new ResultObject(200, "success", response.getUserId());
    }
}
